﻿using AutoMapper;
using MediatR;
using MyRabbit.Application.Command;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyRabbit.Application.CommandHandler
{
    public class ProductUpdateCommandHandler : IRequestHandler<ProductUpdateCommand, APIResult<object>>
    {
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 产品仓储
        /// </summary>
        private readonly IRepository<Product> proRep;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="proRep"></param>
        public ProductUpdateCommandHandler(IMapper mapper, IRepository<Product> proRep)
        {
            this.mapper = mapper;
            this.proRep = proRep;
        }


        public async Task<APIResult<object>> Handle(ProductUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = Codes.修改成功;
            result.Message = Codes.修改成功.ToString();

            try
            {
                var entity = mapper.Map<Product>(request);
                entity.UpdatedTime = DateTime.Now;
                await proRep.UpdateAsync(entity);
            }
            catch (Exception ex)
            {
                result.Code = Codes.修改失败;
                result.Message = Codes.修改失败.ToString() + "，" + ex.Message;
            }

            return await Task.FromResult(result);
        }
    }
}
